package com.py.credit.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.service.CreditTotalService;
import com.py.credit.service.KhzlService;

import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping("/khzl")
public class KhzlController {
	
	@Autowired
	private RemoteBaseService remoteBaseService;
	@Autowired
	private KhzlService khzlService;
	
	@Value("${absolutepath}")
	private String absolutepath;

	@IgnoreAuthority
    @RequestMapping(value = "/getList.json")
    public RestServiceResult<List<Map<String, Object>>> getList(
            @RequestParam(value = "zlmc", defaultValue = "", required = true) String zlmc,
            Page page, HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        SysUser userInfo = null;
        String rolename="";
		 Long deptId=null;
		 Long userID=null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("CreditTotalController#getList",
                        "未获取到当前用户信息！");
                return result;
            }
        	//获取当前用户所属部门
			deptId=	userInfo.getOfficeId();
			//获取当前用户ID
			userID = userInfo.getId();
			//获取用户角色信息
			rolename = userInfo.getRoleName();
        } else {
            ExceptionLogger.error("CreditTotalController#getList",
                    "未获取到当前用户信息！");
        }

    	List<Map<String,Object>> data  = new ArrayList<Map<String,Object>>();
        try {
        	//系统管理员看到所有采集数据
			if(rolename.equals("系统管理员")) {
				data = khzlService.getListForPage(zlmc,page,null,null);
			}else if(rolename.equals("部门管理员")){//部门管理员看到本部门所有采集数据
				data = khzlService.getListForPage(zlmc,page,deptId,null);
			}else {//普通用户看到本部门自己所有采集数据
				data = khzlService.getListForPage(zlmc,page,deptId,userID);
			}
        

            result = new RestServiceResult<>(page.getTotalCount(), data);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("系统异常！");
            return result;
        }
    }
	
	@IgnoreAuthority
	@RequestMapping(value = "/addKhzl.json")
	public RestServiceResult<Object> addKhzl(HttpServletRequest request,
			@RequestParam(value = "file") CommonsMultipartFile file
			) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("CreditTotalController#addCreditranking", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		long deptId = userInfo.getOfficeId();
		long userId = userInfo.getId();
		String userName = userInfo.getRealName();
		try {

	        String batchId = UuidUtil.getInstance().getUUid();
	        // 文件存储路径
	        StringBuilder pathFile = new StringBuilder(200);
	        pathFile.append(File.separator);
	        pathFile.append(userInfo.getId());
	      	      
	        // 获取文件名
	        String  fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")).replace(" ", "");

	        String    fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
                    file.getOriginalFilename().length());
	       
	        String path =absolutepath + "/zlzx" + pathFile.toString()+File.separator+fileName+fileType;
	        // 先存储文件
	        fileUpload(file, absolutepath + "/zlzx" + pathFile.toString(),fileName,fileType);
			khzlService.addKhzl(batchId,deptId,userName,fileName,path,userId);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("CreditTotalController#addKhzl", "新增资料异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("新增资料异常！");
			return result;
		}
	}
	@IgnoreAuthority
	@RequestMapping(value = "/updateKhzl.json")
	public RestServiceResult<Object> updateKhzl(		
			@RequestParam(value = "ids", defaultValue = "", required = true) String ids,
			@RequestParam(value = "type", defaultValue = "", required = true) String type,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition
			) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		List<String> idList = java.util.Arrays.asList(ids.split(","));
		try {		
			for(String id:idList) {
				khzlService.updateKhzl(id,type,condition);
			}				
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("CreditTotalController#deleteKhzl", "操作异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("操作异常！");
			return result;
		}
	}
	@IgnoreAuthority
	@RequestMapping("/export.json")
	public void exportxzxkTemplate(String url, HttpServletResponse response) throws IOException {
		
		FileUtils.downloadFile(URLDecoder.decode(url, "UTF-8"), response);

	}
	  private void fileUpload(MultipartFile file, String pathFile,String fileName, String fileType)
	            throws IllegalStateException, IOException {
	        File uploadFile = null;

	        File dirPath = new File(pathFile);
	        uploadFile = new File(pathFile + File.separator +fileName+ fileType);
	        if (!dirPath.exists()) {
	            uploadFile.mkdirs();
	        }
	        file.transferTo(uploadFile);

	    }
}
